#!/user/bin/env python
# -*- coding:utf-8 -*-
# author : 洛月
# email  : 2870093961@qq.com
# created: 2021-08-10 08:00
# updated: 2022-05-05 16:19
from flask import Flask, request, jsonify
import requests
import time

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False


def proxy_request(form):
    kwargs = {
        "headers": {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                          "AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/92.0.4515.131 Safari/537.36"},
        "timeout": 5,
        "retry": 2,
        "wait": 0.5,
    }
    kwargs.update(form)
    method = kwargs.pop("method")
    retry = int(kwargs.pop("retry"))
    wait = float(kwargs.pop("wait"))
    url = kwargs.pop("url")
    err = None
    for i in range(retry):
        try:
            return True, requests.request(method, url, **kwargs).content
        except Exception as e:
            err = e
            time.sleep(wait)
    return False, err


@app.before_request
def proxy():
    try:
        form = request.form.to_dict()
        state, content = proxy_request(form)
        if state:
            return content, 200
        else:
            return jsonify({"msg": str(content)}), 500
    except Exception as e:
        return jsonify({"msg": str(e)}), 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9000)
